/**
 iTextUploader
 (C) 2008 MyselftDev (myselftdev@gmail.com)
 
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/* Revision: $Id: PreferencesTableController.m 105 2009-04-09 15:28:25Z myselftdev $ */

#import "PreferencesTableController.h"

// Dummy interface to avoid some warnings
@interface NSObject (PreferencesTableController)
- (id) mainView;
- (id) navBar;
- (id) loadHome;
- (id) home;
- (void) enableAutomaticUpload:(BOOL)value;
@end

@implementation PreferencesTableController

@synthesize showAdvanced;

- (id)initWithData:(PreferencesData*)dataObject parent:(id)parentObject
{
	if(self = [super init])
	{
		data = [dataObject retain];
		parent = [parentObject retain];
		
		BOOL disableSwitch = NO;
		
		// Username
		usernameCell = [[UITableViewCell alloc] init];
		usernameCell.text = @"Username";
		usernameCell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		usernameField = [ [UITextField alloc]
						 initWithFrame:CGRectMake(usernameCell.frame.origin.x + 110.0,
												  usernameCell.frame.origin.y + 8.0,
												  usernameCell.frame.size.width - 130.0,
												  31.0)];
		usernameField.borderStyle = UITextBorderStyleNone;
		usernameField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
		usernameField.autocorrectionType = UITextAutocorrectionTypeNo;
		usernameField.autocapitalizationType = UITextAutocapitalizationTypeNone;
		usernameField.returnKeyType = UIReturnKeyDone;
		usernameField.delegate = self;
		usernameField.placeholder = @"YouArchive.It username";
		usernameField.font = [UIFont fontWithName:@"Helvetica" size:15];
		usernameField.clearButtonMode = UITextFieldViewModeWhileEditing;
		NSString *username = [data getData:@"username"];
		if(![username isEqualToString:@""])
		{
			usernameField.text = username;
		}
		else
		{
			disableSwitch = YES;
		}
		[usernameCell.contentView addSubview:usernameField];
		
		// Password
		passwordCell = [[UITableViewCell alloc] init];
		passwordCell.text = @"Password";
		passwordCell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		passwordField = [ [UITextField alloc]
						 initWithFrame:CGRectMake(passwordCell.frame.origin.x + 110.0,
												  passwordCell.frame.origin.y + 12.0,
												  passwordCell.frame.size.width - 130.0,
												  31.0)];
		usernameField.borderStyle = UITextBorderStyleNone;
		usernameField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
		passwordField.clearsOnBeginEditing = YES;
		passwordField.secureTextEntry = YES;
		passwordField.autocorrectionType = UITextAutocorrectionTypeNo;
		passwordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
		passwordField.returnKeyType = UIReturnKeyDone;
		passwordField.delegate = self;
		passwordField.placeholder = @"YouArchive.It password";
		passwordField.font = [UIFont fontWithName:@"Helvetica" size:15];
		NSString *password = [data getData:@"password"];
		if(![password isEqualToString:@""])
		{
			passwordField.text = password;
		}
		else
		{
			disableSwitch = YES;
		}
		[passwordCell.contentView addSubview:passwordField];
		
		// Donate cell
		donateCell = [ [UITableViewCell alloc] init];
		donateCell.text = nil;
		donateCell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		donateButton = [UIButton buttonWithType:UIButtonTypeCustom];
		[donateButton setImage:[UIImage imageNamed:@"Paypal.gif"] forState:UIControlStateNormal];
		donateButton.frame = CGRectMake(
										(donateCell.frame.size.width - 62.0) / 2,
										donateCell.frame.origin.y + 6.0,
										62.0,
										31.0);
		[donateButton addTarget:parent action:@selector(donateButtonClicked) forControlEvents:UIControlEventTouchUpInside];
		
		donateText = [ [UITextView alloc] init];
		donateText.text = @"If you like this app, please consider donating. Your support allows us to improve the service every day.\nAlso, users who donate 5€ or more will become VIP.\nVIP users can use Automatic Upload, store much more messages and don't see ads in iTextUploaer.";
		donateText.editable = NO;
		donateText.userInteractionEnabled = NO;
		donateText.font = [UIFont fontWithName:@"Helvetica" size:15.0];
		donateText.textAlignment = UITextAlignmentCenter;
		donateText.frame = CGRectMake(
									  (donateCell.contentView.frame.size.width - 280.0) / 2,
									  donateCell.contentView.frame.origin.y + 35.0,
									  280.0,
									  162.0);
		[donateCell.contentView addSubview:donateText];
		[donateCell.contentView addSubview:donateButton];
		
		// Advanced options link
		advancedCell = [ [UITableViewCell alloc] init];
		advancedCell.text = @"Advanced options";
		advancedCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		
		// Privacy mode switch
		privacyCell = [ [UITableViewCell alloc] init];
		privacyCell.selectionStyle = UITableViewCellSelectionStyleNone;
		privacyCell.text = @"Privacy mode";
		
		privacySwitch = [ [UISwitch alloc]
						 initWithFrame:CGRectMake(privacyCell.frame.origin.x + 195.0,
												  privacyCell.frame.origin.y + 8.0,
												  10.0, // UISwitch ignore size values
												  10.0)];
		[privacySwitch addTarget:self action:@selector(privacySwitchChanged) forControlEvents:UIControlEventValueChanged];
		NSNumber *privacyNumber = [data getData:@"privacymode"];
		BOOL privacyValue;
		if(privacyNumber == nil)
		{
			privacyValue = NO;
		}
		else
		{
			privacyValue = [privacyNumber boolValue];
		}
		privacySwitch.on = privacyValue;
		if(disableSwitch)
		{
			privacySwitch.enabled = NO;
		}
		[privacyCell.contentView addSubview:privacySwitch];
		
		// Automatic Upload switch
		automaticUploadCell = [ [UITableViewCell alloc] init];
		automaticUploadCell.selectionStyle = UITableViewCellSelectionStyleNone;
		automaticUploadCell.text = @"Automatic Upload";
		
		automaticUploadSwitch = [ [UISwitch alloc]
						 initWithFrame:CGRectMake(automaticUploadCell.frame.origin.x + 195.0,
												  automaticUploadCell.frame.origin.y + 8.0,
												  10.0, // UISwitch ignore size values
												  10.0)];
		[automaticUploadSwitch addTarget:self action:@selector(automaticUploadSwitchChanged) forControlEvents:UIControlEventValueChanged];
		NSNumber *automaticUploadNumber = [data getData:@"AutomaticUpload"];
		BOOL automaticUploadValue;
		if(automaticUploadNumber == nil)
		{
			automaticUploadValue = NO;
		}
		else
		{
			automaticUploadValue = [automaticUploadNumber boolValue];
		}
		automaticUploadSwitch.on = automaticUploadValue;
		[automaticUploadCell.contentView addSubview:automaticUploadSwitch];
		
		// Automatic Upload use over carrier data network switch
		automaticUploadNetworkCell = [ [UITableViewCell alloc] init];
		automaticUploadNetworkCell.selectionStyle = UITableViewCellSelectionStyleNone;
		automaticUploadNetworkCell.text = @"Enable over EDGE/3G";
		
		automaticUploadNetworkSwitch = [ [UISwitch alloc]
								 initWithFrame:CGRectMake(automaticUploadNetworkCell.frame.origin.x + 195.0,
														  automaticUploadNetworkCell.frame.origin.y + 8.0,
														  10.0, // UISwitch ignore size values
														  10.0)];
		[automaticUploadNetworkSwitch addTarget:self action:@selector(automaticUploadNetworkSwitchChanged) forControlEvents:UIControlEventValueChanged];
		NSNumber *automaticUploadNetworkNumber = [data getData:@"AutomaticUploadNetwork"];
		BOOL automaticUploadNetworkValue;
		if(automaticUploadNetworkNumber == nil)
		{
			automaticUploadNetworkValue = NO;
		}
		else
		{
			automaticUploadNetworkValue = [automaticUploadNetworkNumber boolValue];
		}
		automaticUploadNetworkSwitch.on = automaticUploadNetworkValue;
		[automaticUploadNetworkCell.contentView addSubview:automaticUploadNetworkSwitch];
		
		[self automaticUploadSwitchChanged];
	}
	return self;
}

- (void)dealloc
{
	[usernameCell release];
	[passwordCell release];
	[usernameField release];
	[passwordField release];
	[donateCell release];
	[donateText release];
	[donateButton release];
	
	[privacyCell release];
	[privacySwitch release];
	[automaticUploadCell release];
	[automaticUploadSwitch release];
	[automaticUploadNetworkCell release];
	[automaticUploadNetworkSwitch release];
	
	[data release];
	[parent release];
	
	[super dealloc];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	if(!showAdvanced)
	{
		return 3;
	}
	else
	{
		return 2;
	}
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if(!showAdvanced)
	{
		switch (section) {
			case 0:
				return 2;
				break;
				
			case 1:
				return 1;
				break;
				
			case 2:
				return 1;
				break;
		}
	}
	else
	{
		switch (section) {
			case 0:
				return 1;
				break;
				
			case 1:
				return 2;
				break;
		}
	}
	
	return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	if(!showAdvanced)
	{
		if(section == 0)
		{
			return @"YouArchive.It login data";
		}
	}
	
	return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(!showAdvanced)
	{
		if(indexPath.section == 0)
		{
			switch (indexPath.row)
			{
				case 0:
					return usernameCell;
					break;
				case 1:
					return passwordCell;
					break;
				default:
					return nil;
					break;
			}
		}
		else if(indexPath.section == 1)
		{
			// There's just one row here :)
			return advancedCell;
		}
		else
		{
			return donateCell;
		}
	}
	else
	{
		if(indexPath.section == 0)
		{
			return privacyCell;
		}
		else
		{
			switch (indexPath.row)
			{
				case 0:
					return automaticUploadCell;
					break;
				case 1:
					return automaticUploadNetworkCell;
					break;
				default:
					return nil;
					break;
			}
		}
	}
	
	return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
	if(showAdvanced)
	{
		if(section == 0)
		{
			return @"When enabled, you will be asked to type in your log in password every time you want to browse your archive within iTextUploader.";
		}
		else if(section == 1)
		{
			return @"For technical reasons, only VIP users, that donated 5€ or more, can use Automatic Upload.";
		}
	}
	
	return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(!showAdvanced && indexPath.section == 2)
	{
		return 200.0;
	}
	else
	{
		return 44.0;
	}
	
	return 0.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(!showAdvanced && indexPath.section == 1 && indexPath.row == 0)
	{
		UINavigationItem *back = [[UINavigationItem alloc] initWithTitle:@"Advanced"];
		[ [ [parent mainView] navBar] pushNavigationItem:back animated:NO];
	}
}

-(void)privacySwitchChanged
{	
	TextAlertView *alert = [[TextAlertView alloc] initWithTitle:@"Password" message:@"Please insert your YouArchive.It login password to confirm." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
	alert.textField.secureTextEntry = YES;
	alert.textField.autocorrectionType = UITextAutocorrectionTypeNo;
	alert.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
	[alert show];
	[alert autorelease];
}

- (void)automaticUploadSwitchChanged
{
	BOOL newVal = automaticUploadSwitch.on;
	if(![[data getData:@"VIP"] boolValue])
	{
		newVal = NO;
		automaticUploadSwitch.on = NO;
		automaticUploadSwitch.enabled = NO;
	}
	else
	{
		automaticUploadSwitch.enabled = YES;
	}
	
	automaticUploadNetworkSwitch.enabled = newVal;
	
	if(newVal != [[data getData:@"AutomaticUpload"] boolValue])
	{
		[data setValue:[NSNumber numberWithBool:newVal] forData:@"AutomaticUpload"];
		[parent enableAutomaticUpload:newVal];
	}
}

- (void)automaticUploadNetworkSwitchChanged
{
	BOOL newVal = automaticUploadNetworkSwitch.on;
	[data setValue:[NSNumber numberWithBool:newVal] forData:@"AutomaticUploadNetwork"];
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	TextAlertView *alertView = (TextAlertView*) actionSheet;
	
	if(buttonIndex > 0 && [[data getData:@"password"] isEqualToString:alertView.textField.text])
	{
		[data setValue:[NSNumber numberWithBool:privacySwitch.on] forData:@"privacymode"];
		
		NSString *message = nil;
		if(privacySwitch.on)
		{
			message = @"Privacy Mode enabled";
		}
		else
		{
			message = @"Privacy Mode disabled";
		}
		
		UIAlertView *alertMessage = [ [UIAlertView alloc] initWithTitle:message message:@"In order to activate the changes you'll need to restart iTextUploader" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertMessage show];
		[alertMessage autorelease];
	}
	else
	{
		BOOL newVal = !privacySwitch.on;
		[data setValue:[NSNumber numberWithBool:newVal] forData:@"privacymode"];
		privacySwitch.on = newVal;
		UIAlertView *alertMessage = [ [UIAlertView alloc] initWithTitle:@"Incorrect password" message:@"The password you inserted is not correct." delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
		[alertMessage show];
		[alertMessage autorelease];
	}
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	if(![passwordField.text isEqualToString:[data getData:@"password"]])
	{
		privacySwitch.on = NO;
	}
	
	if(usernameField.text != nil)
	{
		[data setValue:usernameField.text forData:@"username"];
	}
	
	if(passwordField.text != nil)
	{
		[data setValue:passwordField.text forData:@"password"];
	}
	
	[textField resignFirstResponder];
	
	if(![[data getData:@"username"] isEqualToString:@""] && ![[data getData:@"password"] isEqualToString:@""])
	{
		[[parent home] loadHome];
		privacySwitch.enabled = YES;
	}
	else
	{
		privacySwitch.enabled = NO;
	}
	
	return NO;
}

@end